"""
上下文 | 模型
"""

from pymongo.synchronous.client_session import ClientSession

from models import AnyTypeBase
from models.other import RequestRoute
from models.po import UserPO
from my_typing import *
from utils.data_utils.special import ObjectIdStr
from utils.validator_utils.pydantic_validator.field import (
    CharField,
    NormalField,
)


class RequestContext(AnyTypeBase):
    """ 请求上下文 | Model  """

    request_id: StrOrNone = CharField(None, title="请求 ID", min_length=28, max_length=28)
    request_ip: StrOrNone = CharField(None, title="请求 IP", min_length=7, max_length=15)
    request_time: DateTimeOrNone = NormalField(None, title="请求时间")
    request_route: RequestRoute = NormalField(None, title="请求路由信息")
    trace_id: StrOrNone = CharField(None, title="链路 ID", min_length=40, max_length=41)
    user: UserPO | None = NormalField(None, title="用户")
    mongo_session: ClientSession | None = NormalField(None, title="MongoDB Session（用于开启事务）")

    @property
    def user_id(self) -> ObjectIdStr | None:
        """ 获取用户 ID """

        if not self.user:
            return None

        return self.user.id

    @property
    def is_authenticated(self) -> bool:
        """ 是否验证通过 """

        return bool(self.user)

    @property
    def is_admin(self) -> bool:
        """ 是否是管理员 """

        return bool(
            self.user
            and self.user.is_admin
        )
